<?php

/**
 * 接口控制器基类
 * 
 */
class apiAction extends Action{

	public function _initialize() {
		
		//检查是否登录
		$this->_checkLogin();
		//当前登录用户的信息
		$this->user = session('user');
		//检查访问权限
		$this->_checkAccess();
    }
	
	/**
	 * 检查用户是否登录
	 */
	private function _checkLogin(){
		//无需验证登录状态的模块(名称全小写)
		$publicModule = array(
			'user/login',
			'demo/camera',
		);
		if(session('user') == FALSE && in_array(strtolower(MODULE_NAME).'/'.strtolower(ACTION_NAME), $publicModule) == FALSE){
			$this->ajaxReturn(300, L('please_login'));
		}
	}
	
	/**
	 * 检查模块访问权限
	 */
	private function _checkAccess(){
		$access = C('API-ACCESS');
		$tag	= MODULE_NAME.'-'.ACTION_NAME;
		if(isset($access[$tag])){
			if(! in_array($this->user['roleId'], $access[$tag]['roleId'])){
				$this->ajaxReturn(403, $access[$tag]['errorMsg']);
			}
		}
	}

	/**
	 * 接口响应方法
	 * @param int $status	状态值（200：成功；300：失败）
     * @param string $msg	状态说明
     * @param mixed $data	响应数据
	 */
	protected function ajaxReturn($status, $msg='', $data='', $type='JSON'){
		$res['status']	= $status;
		$res['msg']		= $msg;
		if($data){
			$res['data']= $data;
		}
		//保存错误访问日志
		if($status == 300){
			$this->saveRequestInfo($msg);
		}
		parent::ajaxReturn($res, $type);
	}
	
	/**
     * 上传文件默认规则定义
     */
    protected function _upload_init($upload,$allow_exts=null) {
        $allow_max = C('PIN_ATTR_ALLOW_SIZE'); //读取配置
        $allow_exts || $allow_exts = explode(',', C('pin_attr_allow_exts')); //读取配置
        $allow_max && $upload->maxSize = $allow_max * 1024;   //文件大小限制
        $allow_exts && $upload->allowExts = $allow_exts;  //文件类型限制
        $upload->saveRule = 'uniqid';
        return $upload;
    }

    /**
     * 上传文件
     */
    protected function _upload($file, $dir = '', $thumb = array(), $save_rule='uniqid',$allow_exts=null) {
        $upload = new UploadFile();
        if ($dir) {
            $upload_path = C('pin_attach_path') . $dir . '/';
            $upload->savePath = $upload_path;
        }
        if ($thumb) {
            $upload->thumb = true;
            $upload->thumbMaxWidth = $thumb['width'];
            $upload->thumbMaxHeight = $thumb['height'];
            $upload->thumbPrefix = isset($thumb['Prefix']) ? $thumb['Prefix'] : 'thumb_';
            //$upload->thumbSuffix = isset($thumb['suffix']) ? $thumb['suffix'] : '_thumb';
            $upload->thumbExt = isset($thumb['ext']) ? $thumb['ext'] : '';
            $upload->thumbRemoveOrigin = isset($thumb['remove_origin']) ? true : false;
        }
        //自定义上传规则
        $upload = $this->_upload_init($upload,$allow_exts);
        if( $save_rule!='uniqid' ){
            $upload->saveRule = $save_rule;
        }

        if ($result = $upload->uploadOne($file)) {
            return array('error'=>0, 'info'=>$result);
        } else {
            return array('error'=>1, 'info'=>$upload->getErrorMsg());
        }
    }
	
	/**
	 * 保存附件信息
	 * @param string $name 表单字段名称
	 */
	protected function saveAttachment($name){
		$res = array('data'=>'', 'error'=>'');
		$dir = rtrim('/'.MODULE_NAME.'/', '/').'/'.date('Ymd');
		
		if(! file_exists(C('pin_attach_path').$dir)){
			mkdir($dir, 0777);
		}
		
		$upload = $this->_upload($_FILES[$name], $dir, array('width'=>200, 'height'=>200));

		if($upload['error']){
			$res['error'] = $upload['info'];
		}else{
			foreach($upload['info'] as $row){
				$type = explode('/', $row['type']);

				$data[$type[0]][] = $dir.'/'.$row['savename'];
			}
			$res['data'] = serialize($data);
		}
		return $res;
	}
	
	/**
	 * 保存图片信息
	 * @param string $name 表单字段名称
	 */
	protected function saveImages($name){
		$res = array('data'=>'', 'error'=>'');
		$dir = rtrim('/'.MODULE_NAME.'/', '/').'/'.date('Ymd');
		
		if(! file_exists(C('pin_attach_path').$dir)){
			mkdir($dir, 0777);
		}
		
		$upload = $this->_upload($_FILES[$name], $dir, array('width'=>200, 'height'=>200), 'uniqid', array('jpg','png','jpeg','gif','bmp'));

		if($upload['error']){
			$res['error'] = $upload['info'];
		}else{
			foreach($upload['info'] as $row){
				$data[] = date('Ymd').'/'.$row['savename'];
			}
			$res['data'] = serialize($data);
		}
		return $res;
	}
	
	/**
	 * 保存请求信息
	 */
	public function saveRequestInfo($response=''){
		$str = 'Request->';
		if(! empty($_GET)){
			$str .= "{GET:";
			foreach($_GET as $key=>$val){
				$str .="[";
				if(is_array($val)){
					foreach ($val as $skey=>$sval){
						$str .= trim("{$key}=>({$skey}=$sval),", ',');
					}
				}else{
					$str .="{$key}=>{$val}";
				}
				$str .="]";
			}
			$str .= "}";
		}
		if(! empty($_POST)){
			$str .= "{POST:";
			foreach($_POST as $key=>$val){
				$str .="[";
				if(is_array($val)){
					foreach ($val as $skey=>$sval){
						$str .= trim("{$key}=>({$skey}=$sval),", ',');
					}
				}else{
					$str .="{$key}=>{$val}";
				}
				$str .="]";
			}
			$str .= "}";
		}
		$str .= 'Response->{'.$response.'}';
		
		$filename= C('pin_attach_path').'DebugLog/RequestInfo_'.date('Y-m-d').'.log';
		if(! file_exists($filename)){
			touch($filename);
		}
		
		$logInfo = "[".date('Y-m-d H:i:s')."] [".get_client_ip()."] {$str}\r\n";
		$logFile = fopen($filename, "w");
		fwrite($logFile, $logInfo);
		fclose($logFile);   //关闭文件资源
	}
}

/* End of file apiAction.class.php */